//
//  KoiWebVieww.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 20.04.25.
//

import Foundation
import SwiftUI
import WebKit

struct KoiWebView : View {
    
    @State private var isLoading = true
    @State private var refresh = false
    @State private var showRetry = false
    var url: String
    @State var postData: Data? = nil
    
    var body: some View {
        ZStack {
            WebView(isLoading: $isLoading, refresh: $refresh, showRetry: $showRetry, url: url, postData: postData)
                .frame(maxWidth: .infinity, maxHeight: .infinity)
            if isLoading {
                ProgressView()
            }
            if showRetry {
                Button (action: {
                    showRetry = false
                    isLoading = true
                    refresh = true
                }) {
                    Text("重新加载")
                        .font(.system(size: 14))
                        .foregroundColor(Color.koiColorPrimary)
                        .padding(EdgeInsets(top: 10, leading: 16, bottom: 10, trailing: 16))
                        .background(Color.koiColorBackgroundItem)
                        .cornerRadius(20)
                }
            }
        }
    }
}

struct WebView: UIViewRepresentable {
    @Binding var isLoading: Bool
    @Binding var refresh: Bool
    @Binding var showRetry: Bool
    let url: String
    let postData: Data?
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    func updateUIView(_ webView: WKWebView, context: Context) {
        if refresh {
            load(webView) // Reload the WebView when refresh is triggered
            DispatchQueue.main.async {
                self.refresh = false // Reset the refresh flag
            }
        }
    }
    
    private func load(_ webView: WKWebView) {
        var request = URLRequest(url: URL(string: url)!)
        if let postData = postData {
            request.httpMethod = "post"
            request.httpBody = postData
            request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        }
        webView.load(request)
    }
    
    func makeUIView(context: Context) -> WKWebView {
        let webView = WKWebView()
        webView.navigationDelegate = context.coordinator
        load(webView)
        
        return webView
    }
    
    class Coordinator: NSObject, WKNavigationDelegate{
            var parent: WebView

            init(_ parent: WebView) {
                self.parent = parent
                print("初始化")
            }

            func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
                parent.isLoading = true
                print("开始加载")
            }

            func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
                parent.isLoading = false
                print("加载完成")
            }

            func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
                parent.isLoading = false
                parent.showRetry = true
                print("加载出错")
            }
            
            func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: any Error) {
                parent.isLoading = false
                parent.showRetry = true
                print("加载出错")
            }
        }
}
